package org.steven.crm.core.service.weixin;

import org.steven.crm.core.exception.ServiceException;
import org.steven.crm.core.service.system.SystemConfigService;
import org.steven.crm.core.utils.http.SimpleHttpClient;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.log4j.Logger;
import weixin.popular.api.SnsAPI;
import weixin.popular.bean.sns.SnsToken;

import java.util.Map;

/**
 * @Author wuzw
 * @Date 2023/6/24 12:47
 * @Version 1.0
 */
public class WeixinUserService {
    private static Logger logger = Logger.getLogger(WeixinUserService.class);
    private static final String LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static SystemConfigService systemConfigService = new SystemConfigService();

    public SnsToken getSnsTokenByCode(String appId, String appSecret, String code) {
        SnsToken snsToken = SnsAPI.oauth2AccessToken(appId, appSecret, code);
        return snsToken;
    }

    public String getOauthLink(String appId, String returnUrl) {
        String oauthUrl = SnsAPI.connectOauth2Authorize(appId, returnUrl, false, "");
        logger.info("oauthUrl " + oauthUrl);
        return oauthUrl;
    }

    public String getOpenId(String jsCode, String wxAppId, String wxSecret) throws Exception {
        String param = "appid=" + wxAppId + "&secret=" + wxSecret + "&js_code=" + jsCode
                + "&grant_type=authorization_code";
        String response = SimpleHttpClient.get(LOGIN_URL, param);

        Map<String, Object> responseMap = getDataAsMapObject(response);

        return responseMap.get("openid").toString();
    }

    private static Map<String, Object> getDataAsMapObject(String json) throws Exception {
        Map<String, Object> responseMap = JSON.parseObject(json, new TypeReference<Map<String, Object>>(){});
        if (null == responseMap) {
            throw new ServiceException("unknow error");
        }
        if (responseMap.containsKey("errcode") && !"0".equals(responseMap.get("errcode").toString())) {
            logger.error("getDataAsMapObject error, response:" + json);
            throw new ServiceException(responseMap.get("errmsg").toString());
        }

        return responseMap;
    }
}
